package com.chucang.shucang.common.base.advice;

import com.chucang.shucang.common.base.exception.ErrorCode;
import com.chucang.shucang.common.base.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常捕获
 *
 * @description: ControllerAdvice
 * @author: flitsneak
 * @date: 2022-09-12
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.chucang.shucang")
public class GlobalExceptionControllerAdvice {

    /**
     * jsr303拦截
     *
     * @param e 校验异常
     * @return result
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Map<String, String>> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError ->
                errMap.put(fieldError.getField(), fieldError.getDefaultMessage())
        );
        return R.failed(errMap, ErrorCode.VALIDATION_EXCEPTION.getCode(), ErrorCode.VALIDATION_EXCEPTION.getMsg());
    }

    /**
     * 兜底捕获
     *
     * @param throwable 最大异常
     * @return result
     */
    @ExceptionHandler(value = Throwable.class)
    public R<Map<String, Object>> handleException(Throwable throwable) {
        Map<String, Object> errMap = new HashMap<>();
        errMap.put("errMessage", throwable.getMessage());
        errMap.put("errCause", throwable.getCause());
        errMap.put("errStackTrace", throwable.getStackTrace());
        return R.failed(errMap, ErrorCode.INTERNAL_SERVER_ERROR.getCode(), ErrorCode.INTERNAL_SERVER_ERROR.getMsg());
    }
}